package com.code;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.Global.Global;
import com.database.DBSystem;
import com.example.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

@SuppressLint("DefaultLocale")
public class TK_Login extends Activity {

	private EditText etUser, etPass;
	private Button btLogin, btCancel;
	private final int REQUESTCODE_TKCHONMAU = 100;
	private final int REQUESTCODE_BDCHONMAU = 101;
	private int iChooseTKBD;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tk_login);

		iChooseTKBD = super.getIntent().getExtras().getInt("iChooseTKBD");

		etUser = (EditText) findViewById(R.id.etUser);
		etPass = (EditText) findViewById(R.id.etPass);
		btLogin = (Button) findViewById(R.id.btLogin);
		btCancel = (Button) findViewById(R.id.btCancel);

		LoadUser();

		btLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				if (checkLogin(etUser.getText().toString(), etPass.getText()
						.toString())) {
					Toast.makeText(TK_Login.this, "Đăng nhập thành công!",
							Toast.LENGTH_LONG).show();
					if (iChooseTKBD == Main.CHOOSE_THONGKE) {
						Intent i = new Intent(TK_Login.this, TK_ChonMau.class);
						Bundle b = new Bundle();
						b.putString("user", etUser.getText().toString());
						i.putExtras(b);
						startActivityForResult(i, REQUESTCODE_TKCHONMAU);
					} else {
						startActivityForResult(new Intent(TK_Login.this,
								Chart_ChooseType.class), REQUESTCODE_BDCHONMAU);
					}
					finish();
				} else {
					Toast.makeText(TK_Login.this, "Đăng nhập thất bại!",
							Toast.LENGTH_LONG).show();
				}
			}
		});

		btCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setResult(RESULT_CANCELED);
				finish();
			}
		});

	}

	public Boolean checkLogin(String strUser, String strPass) {
		try {
			String strQuery = "SELECT * FROM Quyen_User WHERE UserName = '"
					+ strUser + "' AND Password = '"
					+ MD5Password(strUser, strPass) + "'";
			ResultSet rs = Global.excuteQuerySQLServer(strQuery);
			if (rs != null) {
				try {
					while (rs.next()) {
						UpdateUser(etUser.getText().toString(), etPass
								.getText().toString());
						Global.UserName = etUser.getText().toString();
						return true;
					}
				} catch (SQLException e) {
					e.printStackTrace();
					return false;
				}
			} else
				return false;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return false;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	@SuppressLint("DefaultLocale")
	public static String MD5Password(String username, String password)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		if (password.equals("")) {
			return "";
		}
		byte[] pwBytes = new String(
				(username.toUpperCase() + password).getBytes(), "UTF-8")
				.getBytes();
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		String strMD5Pass = "";
		byte byteData[] = messageDigest.digest(pwBytes);
		for (int i = 0; i < byteData.length; i++) {
			strMD5Pass += "-"
					+ Integer.toString((byteData[i] & 0xff) + 0x100, 16)
							.toString().toUpperCase().substring(1);
		}
		return strMD5Pass.substring(1);
	}

	private void LoadUser() {
		DBSystem db = new DBSystem(this);
		db.open();
		Cursor cur = db.SelectSystemAll();
		while (cur.moveToNext()) {
			if (cur.getString(11) != null)
				etUser.setText(cur.getString(11).toString());
			if (cur.getString(12) != null)
				etPass.setText(cur.getString(12).toString());
		}
		cur.close();
		db.close();
	}

	private void UpdateUser(String strUser, String strPass) {
		DBSystem db = new DBSystem(this);
		db.open();
		db.UpdateUserNamePassword(strUser, strPass);
		db.close();
	}

}
